package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.BaseDictionaryData;
import com.zuipin.entity.product.EvaluationInfo;
import com.zuipin.entity.product.ProductDetail;
import com.zuipin.entity.product.ProductExtInfo;
import com.zuipin.entity.product.ProductImg;
import com.zuipin.entity.product.ProductInfo;
import com.zuipin.entity.product.ProductPrice;
import com.zuipin.entity.product.TagInfo;
import com.zuipin.entity.shoppingCart.ProRuleSet;
import com.zuipin.entity.shoppingCart.RuleSet;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.PageResult;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.ProductExtInfoMapper;
import com.zuipin.mapper.RuleSetMapper;
import com.zuipin.service.IEvaluationInfoService;
import com.zuipin.service.IProductDetailService;
import com.zuipin.service.IProductExtInfoService;
import com.zuipin.service.IProductImgService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.IProductPriceService;
import com.zuipin.service.IProductPropertyValueService;
import com.zuipin.service.IShoppingCartService;
import com.zuipin.service.ISysUserService;
import com.zuipin.util.Convert;
import com.zuipin.util.DateUtils;
import com.zuipin.util.Pagination;
import com.zuipin.util.RedisUtils;
import com.zuipin.vo.BackExtProDetailVo;
import com.zuipin.vo.BackProInfoPrice;
import com.zuipin.vo.BackProInfoPropertyVo;
import com.zuipin.vo.BackProductPlatformSearchVo;
import com.zuipin.vo.BackProductPlatformVo;
import com.zuipin.vo.IntegralProSearchVo;
import com.zuipin.vo.IntegralProVo;
import com.zuipin.vo.ProductImgVo;
import com.zuipin.vo.ProductPriceVo;
import com.zuipin.vo.SpecialPriceProVo;

import net.sf.json.JSONObject;

/**
 * 商品拓展信息业务类实现
 *
 * @ClassName ProductExtInfoServiceImpl
 * @author wangcongyi
 * @date 2017年5月2日 下午6:13:02
 */
@Service
public class ProductExtInfoServiceImpl implements IProductExtInfoService {
	
	private final Logger					log		= Logger.getLogger(ProductExtInfoServiceImpl.class);
	
	@Autowired
	private RuleSetMapper					ruleSetMapper;
	
	@Resource
	private ProductExtInfoMapper			productExtInfoMapper;
	
	@Resource
	private RedisUtils						redisUtils;
	
	@Resource
	private IShoppingCartService			shoppingCartService;
	
	@Resource
	private IProductInfoService				productInfoService;
	
	@Resource
	private IProductPriceService			productPriceService;
	
	@Resource
	private IProductPropertyValueService	productPropertyValueService;
	
	@Resource
	private IProductDetailService			productDetailService;
	
	@Resource
	private IProductImgService				productImgService;
	
	@Resource
	private ISysUserService					sysUserService;
	
	@Resource
	private IEvaluationInfoService			evaluationInfoService;
	
	@Value("${imgpath.zpDomain}")
	private String							zpDomain;													// 图片拼接域名
	
	@Value("${imgpath.zpThumbnail230x184}")
	private String							zpThumbnail230x184;											// 缩略图拼接路径规格230X184
	
	@Value("${imgpath.zpThumbnail78x65}")
	private String							zpThumbnail78x65;											// 缩略图拼接路径规格78x65
	
	@Value("${imgpath.zpRawImage}")
	private String							zpRawImage;													// 原图拼接路径
	
	private final static String				IMG_URL	= "IMG_URL";
	
	@Override
	public ProductExtInfo selectByProSku(JSONObject object) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.selectByProSku(object);
	}
	
	@Override
	public int updateSkuByProId(Long proId, String proSku) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.updateSkuByProId(proId, proSku);
	}
	
	@Override
	public List<Map<String, Object>> canOnShelf(String newTime) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.canOnShelf(newTime);
	}
	
	@Override
	public List<Map<String, Object>> canOffShelf(String newTime) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.canOffShelf(newTime);
	}
	
	@Override
	public List<ProductExtInfo> findExtProByProId(Long proId) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findExtProByProId(proId);
	}
	
	@Override
	public boolean updateSalesByProSku(JSONObject object) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.updateSalesByProSku(object);
	}
	
	@Override
	public int deleteByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.deleteByPrimaryKey(id);
	}
	
	@Override
	public int insert(ProductExtInfo record) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.insert(record);
	}
	
	@Override
	public boolean insertSelective(ProductExtInfo record) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.insertSelective(record);
	}
	
	@Override
	public ProductExtInfo selectByPrimaryKey(Long id) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public boolean updateByPrimaryKeySelective(ProductExtInfo record) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public int updateByPrimaryKey(ProductExtInfo record) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.updateByPrimaryKey(record);
	}
	
	@Override
	public boolean modifyState(JSONObject object) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.modifyState(object);
	}
	
	@Override
	public List<Map<String, Object>> findProExt(JSONObject parmas) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findProExt(parmas);
	}
	
	@Override
	public ProductExtInfo isExists(JSONObject params) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.isExists(params);
	}
	
	@Override
	public ProductExtInfo selectByProId(JSONObject object) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.selectByProId(object);
	}
	
	@Override
	public ProductExtInfo findProductExtInfoBySku(String proSku, Long sysId) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findProductExtInfoBySku(proSku, sysId);
	}
	
	/**
	 * @description : 取消过期的特价商品
	 * @author : wuhaijun
	 * @date : 2017年5月15日 下午1:56:45
	 */
	@Override
	@Transactional(rollbackFor = { Exception.class })
	public void cancelExpireSpecialPricePro() {
		List<Map<String, Object>> proList = productExtInfoMapper.querySpecialPricePro();
		if (proList == null || proList.size() < 1) {
			return;
		}
		for (Map<String, Object> map : proList) {
			Long id = Convert.toLong(map.get("id"));
			Long sysId = Convert.toLong(map.get("sysId"));
			String proSku = map.get("proSku").toString();
			String device = "";
			String currTime = DateUtils.getCurrentDateTime();
			RuleSet ruleSet = ruleSetMapper.querySpecialPriceRule(sysId, device, currTime, proSku);
			if (ruleSet == null) {
				log.info("###取消过期的特价商品sku为:【" + proSku + "】###");
				productExtInfoMapper.updateSpecialPricePro(id, null, 0, null);
			}
		}
	}
	
	/**
	 * @description : 设置特价商品
	 * @author : wuhaijun
	 * @date : 2017年5月15日 下午1:56:45
	 */
	@Override
	@Transactional(rollbackFor = { Exception.class })
	public void setSpecialPricePro() {
		String currTime = DateUtils.getCurrentDateTime();
		List<RuleSet> ruleSetList = ruleSetMapper.querySpecialPriceRuleByCurrTime(currTime);
		if (ruleSetList == null || ruleSetList.size() < 1) {
			return;
		}
		for (RuleSet ruleSet : ruleSetList) {
			List<ProRuleSet> proRuleSetList = ruleSetMapper.querySpecialPriceProByRuleId(ruleSet.getId());
			if (proRuleSetList == null || proRuleSetList.size() < 1) {
				continue;
			}
			for (ProRuleSet proRuleSet : proRuleSetList) {
				productExtInfoMapper.updateSpecialPricePro(null, proRuleSet.getProSku(), 1, proRuleSet.getSpecialPrice());
			}
		}
	}
	
	@Override
	public List<ProductExtInfo> isSettledTagInfo(List<String> proSkuList, Long tagId) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.isSettledTagInfo(proSkuList, tagId);
	}
	
	@Override
	public List<ProductExtInfo> findExtProByProIdAll(Long proId) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findExtProByProIdAll(proId);
	}
	
	@Override
	public int removeTagInfo(Long sysId, List<String> skus) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.removeTagInfo(sysId, skus);
	}
	
	@Override
	public List<ProductExtInfo> findProExtByTagId(BaseDictionaryData tagInfo) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findProExtByTagId(tagInfo);
	}
	
	@Override
	public int updateTagInfoBatch(TagInfo tagInfo, List<String> proSkuList) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.updateTagInfoBatch(tagInfo, proSkuList);
	}
	
	@Override
	public List<ProductExtInfo> findProExtBySkus(JSONObject params) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findProExtBySkus(params);
	}
	
	@Override
	public void updateStock() throws CustomException {
		// TODO Auto-generated method stub
		boolean flag = redisUtils.exists("pageNum");
		Integer pageNum = 1;
		if (flag) {
			pageNum = Integer.parseInt(redisUtils.get("pageNum"));
		} else {
			redisUtils.set("pageNum", String.valueOf(pageNum));
		}
		JSONObject params = new JSONObject();
		params.put("pageIndex", (pageNum - 1) * ProductExtInfo.PAGE_SIZE);
		params.put("pageSize", ProductExtInfo.PAGE_SIZE);
		String proSkus = productExtInfoMapper.findSkusByOnShelf(params);
		Integer totalRecord = productExtInfoMapper.getTotalRecord();
		// 库存同步
		stockSynchronize(proSkus);
		if (pageNum * ProductExtInfo.PAGE_SIZE > totalRecord) {
			pageNum = 0;
		}
		log.info("###自动更新库存-当前" + pageNum + "页|每页" + ProductExtInfo.PAGE_SIZE + "条|总共" + totalRecord + "条-###");
		// 库存更新后将当前页更新
		redisUtils.set("pageNum", String.valueOf(++pageNum));
	}
	
	@Override
	public void updateStockBySkus(String skus) throws CustomException {
		log.info("###手动同步库存-同步sku:" + skus);
		stockSynchronize(skus);
	}
	
	/**
	 * @remark 库存同步
	 * @param proSkus
	 * @throws CustomException
	 */
	private void stockSynchronize(String proSkus) throws CustomException {
		Map<String, Map<String, Object>> stockMaps = shoppingCartService.findCisBranchStockByProSkus(proSkus);
		String[] skuArr = proSkus.split(",");
		List<Map<String, Object>> list = new ArrayList<>();
		for (int i = 0; i < skuArr.length; i++) {
			Map<String, Object> map = new HashMap<>();
			Map<String, Object> stockMap = stockMaps.get(skuArr[i]);
			BigDecimal stockNum = (BigDecimal) stockMap.get("validStock");
			int validStock = 0;
			short isSoldOut = 0;
			if (null != stockNum && stockNum.intValue() > 0) {
				validStock = stockNum.intValue();
				isSoldOut = 1;
			}
			map.put("proSku", skuArr[i]);
			map.put("stock", validStock);
			map.put("isSoldOut", isSoldOut);
			list.add(map);
		}
		productExtInfoMapper.updateStockBatch(list);
	}
	
	@Override
	public List<Map<String, Object>> findProExtList(List<String> skus, String device, Long sysId) {
		// TODO Auto-generated method stub
		return productExtInfoMapper.findProExtList(skus, device, sysId);
		
	}
	
	@Override
	public List<IntegralProVo> getIntegralPro(IntegralProSearchVo searchVo, Pagination page) {
		
		// 拼接图片路径
		String imgPath = zpDomain + zpRawImage;
		searchVo.setImgPath(imgPath);
		
		// 获取商品的基本信息不包括价格信息
		List<IntegralProVo> list = productExtInfoMapper.getIntegralPro(searchVo, page);
		
		// 填充价格信息
		for (IntegralProVo v : list) {
			ProductPrice p = new ProductPrice();
			p.setProId(v.getProId());
			p.setSysId(searchVo.getSysId());
			// 查询出商品对应的价格类型列表信息
			List<ProductPrice> prices = productPriceService.getSettledPrice(p);
			for (ProductPrice price : prices) {
				
				// 设置积分价
				if (price.getPriceType().equals(ProductPrice.INTEGRAL)) {
					v.setIntegralPrice(price.getPrice().intValue());
				}
				
				// 设置市场价
				if (price.getPriceType().equals(ProductPrice.MARKET)) {
					v.setMarketPrice(price.getPrice());
				}
				
				// 设置醉品价
				if (price.getPriceType().equals(ProductPrice.ZUIPIN)) {
					v.setProPrice(price.getPrice());
				}
			}
		}
		
		return list;
		
	}
	
	/**
	 * 商品上架下架
	 */
	public Result productShelf(Long proExtId, Long sysId, String state, Long updateId) {
		Result<Integer> result = new Result<>();
		JSONObject params = new JSONObject();
		params.put("proExtId", proExtId);
		params.put("sysId", sysId);
		params.put("state", state);
		ProductExtInfo param = selectByPrimaryKey(proExtId);
		if (param == null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("没有查询到平台商品信息");
			log.info("没有查询到平台商品信息");
			return result;
		}
		StringBuilder stateStr = new StringBuilder();
		// 判断是否已经上架或下架状态
		ProductExtInfo productExtInfo = isExists(params);
		ProductInfo productInfo = productInfoService.selectById(param.getProId());
		// 判断用户传值
		if (state.equals(ProductExtInfo.ON_SHELF)) {
			stateStr.append("上架");
			// 判断通用商品是否被禁用
			if (productInfo == null) {
				result.setErrorCode(ErrorCode.ELSE);
				result.setMessage("通用商品被禁用无法上架");
				log.info("通用商品被禁用无法上架！");
				return result;
			}
			// 更新状态之前查询通用商品信息和价格信息~判断
			// 【积分商品：-市场价&积分价设定不得为0或为空；若为空，则TOAST提示，“商品价格为0或为空，不可上架”；】
			// 【正常商品：-市场价&醉品价设定不得为0或为空；若为空，则TOAST提示，“商品价格为0或为空，不可上架”；】
			// 判断 商品是【积分商品】/【正常商品】
			ProductPrice marketPrice = productPriceService.findByType(param.getProId(), sysId, BackProInfoPrice.MARKET);
			if (ProductInfo.YES_EXCHANGE_INTEGRAL.equals(productInfo.getIsExchangeIntegral())) {
				// 积分价
				ProductPrice integralPrice = productPriceService.findByType(param.getProId(), sysId, BackProInfoPrice.INTEGRAL);
				if (marketPrice == null || integralPrice == null || marketPrice.getPrice() == null || marketPrice.getPrice().equals(BigDecimal.ZERO)
						|| integralPrice.getPrice() == null || integralPrice.getPrice().equals(BigDecimal.ZERO)) {
					result.setErrorCode(ErrorCode.ELSE);
					result.setMessage("商品价格为0或为空，不可上架");
					log.info("商品价格为0或为空，不可上架");
					return result;
				}
			} else {
				// 醉品价
				ProductPrice platPrice = productPriceService.findByType(param.getProId(), sysId, BackProInfoPrice.PLAT);
				if (marketPrice == null || platPrice == null || marketPrice.getPrice() == null || marketPrice.getPrice().equals(BigDecimal.ZERO) || platPrice.getPrice() == null
						|| platPrice.getPrice().equals(BigDecimal.ZERO)) {
					result.setErrorCode(ErrorCode.ELSE);
					result.setMessage("商品价格为0或为空，不可上架");
					log.info("商品价格为0或为空，不可上架");
					return result;
				}
			}
			params.put("onShelfTime", DateUtils.getCurrentDateTime());
		} else {
			stateStr.append("下架");
			params.put("offShelfTime", DateUtils.getCurrentDateTime());
		}
		if (null == productExtInfo) {
			
			// 更新状态
			boolean falg = modifyState(params);
			if (falg) {
				result.setErrorCode(ErrorCode.SUCCESS);
				result.setMessage("商品[" + param.getProSku() + "]" + stateStr + "成功！");
				log.info("自动上架商品--定时器---" + "商品[" + param.getProSku() + "]" + stateStr + "成功！");
			} else {
				result.setErrorCode(ErrorCode.ELSE);
				result.setMessage("商品[" + proExtId + "]" + stateStr + "失败！");
				log.info("自动上架商品--定时器---" + "商品[" + proExtId + "]" + stateStr + "失败！");
			}
		} else {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("商品[" + proExtId + "]不可" + stateStr);
			log.info("自动上架商品--定时器---" + "商品[" + proExtId + "]不可" + stateStr);
		}
		return result;
	}
	
	/**
	 * 定时上架下架时间
	 */
	@Override
	public Result timingModifyState(Long proExtId, Long sysId, String state, String timing) {
		Result result = new Result();
		JSONObject params = new JSONObject();
		params.put("proExtId", proExtId);
		params.put("sysId", sysId);
		params.put("state", state);
		// 判断是否已经上架或下架状态
		ProductExtInfo productExtInfo = isExists(params);
		if (productExtInfo != null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("该商品无法执行此操作");
			return result;
		}
		// 判断用户传值
		if (state.equals(ProductExtInfo.ON_SHELF)) {
			// 判断通用商品是否被禁用
			ProductExtInfo param = selectByPrimaryKey(proExtId);
			ProductInfo productInfo = productInfoService.selectById(param.getProId());
			if (productInfo == null) {
				result.setErrorCode(ErrorCode.ELSE);
				result.setMessage("通用商品被禁用无法上架");
				return result;
			}
			// 定时上架时间123
			productExtInfoMapper.updateProOnShelfTime(proExtId, timing);
		} else {
			// 定时下架时间123
			productExtInfoMapper.updateProOffShelfTime(proExtId, timing);
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 查询后台平台SKU管理列表
	 */
	@Override
	public PageResult<List<BackProductPlatformVo>> findByProPlatformSearch(BackProductPlatformSearchVo search, Pagination page, Long sysId) {
		PageResult<List<BackProductPlatformVo>> result = new PageResult<List<BackProductPlatformVo>>();
		List<BackProductPlatformVo> list = productExtInfoMapper.findByProPlatformSearch(search, page, sysId);
		result.setData(list);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setTotal_record(page.getTotalRecord());
		return result;
	}
	
	/**
	 * 查询后台平台SKU详细信息
	 */
	@Override
	public Result<BackExtProDetailVo> findExtProDetail(Long sysId, String proSku) {
		
		Result<BackExtProDetailVo> result = new Result<BackExtProDetailVo>();
		
		// 查询信息
		BackExtProDetailVo backExtProDetail = productExtInfoMapper.findProExtProDetail(sysId, proSku);
		
		if (backExtProDetail == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("未查询到平台商品详细信息");
			return result;
		}
		
		// 查询价格信息集合
		List<ProductPriceVo> productPriceVos = productPriceService.findByProductId(sysId, backExtProDetail.getProId());
		if (productPriceVos != null && productPriceVos.size() > 0) {
			backExtProDetail.setProductPriceVos(productPriceVos);
		}
		
		// 查询属性信息集合
		List<BackProInfoPropertyVo> proInfoPropertyVos = productPropertyValueService.seachProInfoProperty(backExtProDetail.getProId(), sysId);
		backExtProDetail.setProInfoPropertyVos(proInfoPropertyVos);
		
		// 商品详情List<ProductDetail>
		JSONObject params = new JSONObject();
		params.put("proExtId", backExtProDetail.getProExtId());
		params.put("sysId", sysId);
		List<ProductDetail> productDetails = productDetailService.findByProExtId(params);
		backExtProDetail.setProductDetails(productDetails);
		
		// 商品图片设定List<ProductImg>
		JSONObject object = new JSONObject();
		String thumbnailPath = zpDomain + zpThumbnail230x184;
		String rawPath = zpDomain + zpRawImage;
		object.put("proExtId", backExtProDetail.getProExtId());
		object.put("sysId", sysId);
		object.put("thumbnailPath", thumbnailPath);
		object.put("rawPath", rawPath);
		List<ProductImgVo> productImgs = productImgService.selectByProExtIdBack(object);
		backExtProDetail.setProductImgs(productImgs);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setData(backExtProDetail);
		return result;
		
	}
	
	/**
	 * 判断-是否可以增加平台商品
	 * @param ProNo
	 * @param sysId
	 * @return
	 */
	public Result judgeParams(String proSku, Long sysId) {
		Result result = new Result();
		ProductInfo productInfo = productInfoService.selectByProductProSku(proSku);
		if (productInfo == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("该商品不存在");
			return result;
		}
		// 判断状态为“禁用”
		if (ProductInfo.DISABLE.equals(productInfo.getStatus())) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己禁用，不可新增");
			return result;
		}
		// 判断该商品己添加，不可重复添加
		JSONObject params = new JSONObject();
		params.put("proId", productInfo.getId());
		params.put("sysId", sysId);
		ProductExtInfo pExtInfo = selectByProId(params);
		if (pExtInfo != null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己添加，不可重复添加");
			return result;
		}
		return result;
	}
	
	/**
	 * 添加平台SKU
	 */
	@Override
	@Transactional(rollbackFor = { Exception.class })
	public Result createExtPro(BackExtProDetailVo backExtProDetailVo) throws CustomException {
		Result result = new Result();
		// 判断该商品不存在
		ProductInfo productInfo = productInfoService.selectByProductProSku(backExtProDetailVo.getProSku());
		if (productInfo == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("该商品不存在");
			return result;
		}
		// 判断状态为“禁用”
		if (ProductInfo.DISABLE.equals(productInfo.getStatus())) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己禁用，不可新增");
			return result;
		}
		// 判断该商品己添加，不可重复添加
		JSONObject params = new JSONObject();
		params.put("proId", productInfo.getId());
		params.put("sysId", backExtProDetailVo.getSysId());
		ProductExtInfo pExtInfo = selectByProId(params);
		if (pExtInfo != null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己添加，不可重复添加");
			return result;
		}
		// 系统ID必填
		// 添加Ext表格信息 必填主标题 非必填副标题 必填最低购买 非必填最低购买
		ProductExtInfo productExtInfo = new ProductExtInfo();
		BeanUtils.copyProperties(backExtProDetailVo, productExtInfo);
		productExtInfo.setProId(productInfo.getId());
		productExtInfo.setProSku(productInfo.getProSku());
		productExtInfo.setCreateTime(DateUtils.getCurrentDateTime());
		productExtInfo.setIsScareBuying(false);
		productExtInfo.setVirtualStock(new BigDecimal(999));
		productExtInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		productExtInfo.setUpdateId(backExtProDetailVo.getUpdateId());
		productExtInfo.setCreateId(backExtProDetailVo.getUpdateId());
		productExtInfo.setState(ProductExtInfo.OFF_SHELF);
		insertSelective(productExtInfo);
		// 查出刚刚新增的平台ID
		if (productExtInfo.getId() == null) {
			// 抛异常
			throw new CustomException(ErrorCode.PARAM_ABSENT.getCode(), "新增失败");
		}
		// 商品详情添加 =//终端 PC|WAP =////内容
		List<ProductDetail> productDetails = backExtProDetailVo.getProductDetails();
		if (productDetails == null || productDetails.size() <= 0) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置商品详情");
		}
		boolean pcDetai = true;
		for (ProductDetail productDetail : productDetails) {
			// 添加商品详情
			if (ProductDetail.PC_DETAIL.equals(productDetail.getDevice())) {
				pcDetai = false;
			}
			productDetail.setProExtId(productExtInfo.getId());
			productDetail.setSysId(backExtProDetailVo.getSysId());
			productDetail.setCreateTime(DateUtils.getCurrentDateTime());
			productDetail.setCreateId(backExtProDetailVo.getUpdateId());
			productDetail.setDelFlag(false);
			productDetailService.insertSelective(productDetail);
		}
		if (pcDetai) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "PC商品详情为必填");
		}
		// 判断是否有主图
		boolean pcViewFlag = true;
		boolean wapViewFlag = true;
		// 商品图片添加 =//图片地址 =//是否PC端主图 =//是否WAP端主图 =///创建者
		List<ProductImgVo> productImgs = backExtProDetailVo.getProductImgs();
		if (productImgs == null || productImgs.size() == 0) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置商品图片");
		}
		for (ProductImgVo productImg : productImgs) {
			if (productImg.getPcViewTag().equals(ProductImgVo.YES_VIEW_TAG)) {
				pcViewFlag = false;
			}
			if (productImg.getWapViewTag().equals(ProductImgVo.YES_VIEW_TAG)) {
				wapViewFlag = false;
			}
			// 商品图片添加
			ProductImg img = new ProductImg();
			BeanUtils.copyProperties(productImg, img);
			img.setProExtId(productExtInfo.getId());
			img.setType(ProductImg.ALBUM);
			img.setSysId(backExtProDetailVo.getSysId());
			img.setCreateTime(DateUtils.getCurrentDateTime());
			img.setCreateId(backExtProDetailVo.getUpdateId());
			img.setDelFlag(false);
			img.setPcViewTag(productImg.getPcViewTag().equals(ProductImgVo.YES_VIEW_TAG));
			img.setWapViewTag(productImg.getWapViewTag().equals(ProductImgVo.YES_VIEW_TAG));
			productImgService.insertSelective(img);
		}
		if (pcViewFlag && wapViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置主图");
		}
		if (pcViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置PC主图");
		}
		if (wapViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置WAP主图");
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		return result;
	}
	
	/**
	 * 修改平台商品信息
	 */
	@Override
	@Transactional(rollbackFor = { Exception.class })
	public Result updateExtProDetail(BackExtProDetailVo backExtProDetailVo) throws CustomException {
		Result result = new Result();
		// 查询平台信息
		ProductExtInfo productExtInfo = productExtInfoMapper.selectByPrimaryKey(backExtProDetailVo.getProExtId());
		if (productExtInfo == null) {
			result.setErrorCode(ErrorCode.NOT_FIND);
			result.setCnMessage("该平台商品不存在");
			return result;
		}
		ProductInfo productInfo = productInfoService.selectById(productExtInfo.getProId());
		// 判断状态为“禁用”
		if (productInfo == null || ProductInfo.DISABLE.equals(productInfo.getStatus())) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setCnMessage("该商品己禁用或不存在，不可编辑");
			return result;
		}
		
		productExtInfo.setTitle(backExtProDetailVo.getTitle());
		productExtInfo.setSubTitle(backExtProDetailVo.getSubTitle());// 可以为空
		productExtInfo.setBuyLowLimit(backExtProDetailVo.getBuyLowLimit());
		productExtInfo.setBuyUpperLimit(backExtProDetailVo.getBuyUpperLimit());// 可以为空
		productExtInfo.setUpdateId(backExtProDetailVo.getUpdateId());
		productExtInfo.setUpdateTime(DateUtils.getCurrentDateTime());
		// 更新平台信息基础表
		productExtInfoMapper.updateExtProByBack(productExtInfo);
		
		// 假删除商品详情
		productDetailService.deleteByProExtIdAndSysId(backExtProDetailVo.getProExtId(), backExtProDetailVo.getSysId());
		// 添加商品详情
		List<ProductDetail> productDetails = backExtProDetailVo.getProductDetails();
		if (productDetails == null || productDetails.size() <= 0) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置商品详情");
		}
		boolean pcDetai = true;
		for (ProductDetail productDetail : productDetails) {
			// 添加商品详情
			if (ProductDetail.PC_DETAIL.equals(productDetail.getDevice())) {
				pcDetai = false;
			}
			productDetail.setId(null);
			productDetail.setProExtId(backExtProDetailVo.getProExtId());
			productDetail.setSysId(backExtProDetailVo.getSysId());
			productDetail.setUpdateTime(DateUtils.getCurrentDateTime());
			productDetail.setUpdateId(backExtProDetailVo.getUpdateId());
			productDetail.setDelFlag(false);
			productDetailService.insertSelective(productDetail);
		}
		if (pcDetai) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "PC商品详情为必填");
		}
		// 假删除商品图片
		productImgService.deleteByProExtIdAndSysId(backExtProDetailVo.getProExtId(), backExtProDetailVo.getSysId());
		// 判断是否有主图
		boolean pcViewFlag = true;
		boolean wapViewFlag = true;
		// 更新商品图片
		List<ProductImgVo> productImgs = backExtProDetailVo.getProductImgs();
		if (productImgs == null || productImgs.size() == 0) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置商品图片");
		}
		for (ProductImgVo productImg : productImgs) {
			if (productImg.getPcViewTag().equals(ProductImgVo.YES_VIEW_TAG)) {
				pcViewFlag = false;
			}
			if (productImg.getWapViewTag().equals(ProductImgVo.YES_VIEW_TAG)) {
				wapViewFlag = false;
			}
			// 商品图片添加
			ProductImg img = new ProductImg();
			BeanUtils.copyProperties(productImg, img);
			img.setId(null);
			img.setProExtId(backExtProDetailVo.getProExtId());
			img.setType(ProductImg.ALBUM);
			img.setSysId(backExtProDetailVo.getSysId());
			img.setUpdateTime(DateUtils.getCurrentDateTime());
			img.setUpdateId(backExtProDetailVo.getUpdateId());
			img.setDelFlag(false);
			img.setPcViewTag(productImg.getPcViewTag().equals(ProductImgVo.YES_VIEW_TAG));
			img.setWapViewTag(productImg.getWapViewTag().equals(ProductImgVo.YES_VIEW_TAG));
			productImgService.insertSelective(img);
		}
		if (pcViewFlag && wapViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置主图");
		}
		if (pcViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置PC主图");
		}
		if (wapViewFlag) {
			throw new CustomException(ErrorCode.ILLEGAL_PARAM.getCode(), "请设置WAP主图");
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setCnMessage("更新成功");
		return result;
	}
	
	/**
	 * 查询特价商品列表-zhouhuihang
	 */
	@Override
	public Result<List<SpecialPriceProVo>> getSpecialPricePro(String device, Long sysId, Pagination page) {
		PageResult<List<SpecialPriceProVo>> result = new PageResult<List<SpecialPriceProVo>>();
		// 查询特价商品规则（当前时间的特价规则）
		List<SpecialPriceProVo> specialPricePros = ruleSetMapper.getSpecialPriceRule(DateUtils.getCurrentDateTime(), device, page);
		if (specialPricePros == null) {
			result.setErrorCode(ErrorCode.ELSE);
			result.setMessage("当前时间没有特价商品");
			return result;
		}
		int pageTotal = page.getTotalRecord();
		Iterator<SpecialPriceProVo> iter = specialPricePros.iterator();
		while (iter.hasNext()) {
			SpecialPriceProVo specialPro = iter.next();
			// 装配 商品信息 商品价格 商品图片findProExtInfoBySku
			ProductExtInfo proExtInfo = productExtInfoMapper.findProExtInfoBySku(specialPro.getProSku(), sysId);
			ProductInfo proInfo = productInfoService.getProBySku(specialPro.getProSku());
			if (proExtInfo == null || proInfo == null) {
				pageTotal = pageTotal - 1;
				iter.remove();
				continue;
			}
			specialPro.setProExtId(proExtInfo.getId());
			specialPro.setProName(proInfo.getProName());
			specialPro.setTitle(proExtInfo.getTitle());
			specialPro.setSubTitle(proExtInfo.getSubTitle());
			specialPro.setStockNum(proExtInfo.getStockNum());
			specialPro.setAssessmentNum(proExtInfo.getAssessmentNum());
			specialPro.setIsSales(proExtInfo.getIsSales());
			specialPro.setProState(proExtInfo.getState());
			// 装配价格 需求要求需要市场价
			ProductPrice productPrice = productPriceService.findByType(proInfo.getId(), sysId, SpecialPriceProVo.MARKET_PRICE);
			if (productPrice != null) {
				specialPro.setProPrice(productPrice.getPrice());
			}
			// 装配主图
			Map<String, Object> map = productExtInfoMapper.findProAndMainUrlImgByPro(specialPro.getProSku(), device, sysId);
			String mainImgUrl = "";
			if (map.get(IMG_URL) != null) {
				mainImgUrl = (String) map.get(IMG_URL);
			}
			specialPro.setMainImgUrl(mainImgUrl);
		}
		result.setData(specialPricePros);
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("查询成功");
		result.setTotal_record(pageTotal);
		return result;
	}
	
	/**
	 * 
	 * 更新商品好评数
	 * 
	 */
	@Override
	public Result updateAssessmentNum(Long sysId, Long proExtId) {
		// 更新商品好评数~~~~~~
		Result result = new Result();
		Integer assessmentNum = null;
		EvaluationInfo eval = new EvaluationInfo();
		eval.setSysId(sysId);
		eval.setProExtId(proExtId);
		if (proExtId != null) {
			assessmentNum = evaluationInfoService.getPraiseNum(eval);
			if (assessmentNum != null) {
				ProductExtInfo proExt = new ProductExtInfo();
				proExt.setId(proExtId);
				proExt.setAssessmentNum(assessmentNum);
				updateByPrimaryKeySelective(proExt);
			}
		}
		result.setErrorCode(ErrorCode.SUCCESS);
		result.setMessage("更新成功");
		return result;
	}
}
